
#include "../../http.h"
#include "../../sp_scripter.h"
#include "tools/string_util.h"
#include <stdio.h>
#include <stdlib.h>
#include <sstream>
#include "middle/sha2.h"
#include "middle/sha2config.h"

static std::string RandomString(void)
{
    int l = rand() % 64 + 6;
    int i;
    std::string tmp;
    for (i=0; i<l; i++) {
        tmp += (char)((rand() % 26) + 'A');
    }
    return tmp;
}

static std::string GetShaResult(std::string text)
{
    sha2_context    sha256;
    sha2_starts(&sha256, 0);
    sha2_update(&sha256, (unsigned char*)text.c_str(), text.length());
    unsigned char buf1[32];
    sha2_finish(&sha256, buf1);
    std::string result;
    int i;
    for (i=0; i<32; i++) {
        char    temp[100];
        sprintf(temp, "%02X", buf1[i]);
        result += temp;
    }
    return result;
}

static void Record(std::string text, std::string expect, std::string stbr)
{
}


extern "C" void run(const std::string& localfile, const Http::Param& para, lpfnReply reply)
{
#if 0
    std::string file(localfile.c_str());
    file += ".html";

    FILE * fp = fopen(file.c_str(), "rb");
    if (!fp) {
        std::string tmp = "cannot found html file.";
        reply(200, tmp.c_str(), tmp.length());
        return;
    }

    fseek(fp, 0, SEEK_END);
    int len = ftell(fp);
    fseek(fp, 0, SEEK_SET);
    int total = 0;
    std::string ff;
    while (total < len) {
        char    buffer[4096];
        int ret = fread(buffer, 1, 4096, fp);
        if (ret <= 0)
            break;
        buffer[ret] = '\0';
        ff += buffer;
        total += ret;
    }
    fclose(fp);


    reply(200, ff.c_str(), ff.length());
#else
    std::string text = RandomString();
    std::stringstream   oss;
    oss << "<html><head></head>\n";
    oss << "<script>\n";
    oss << "fcuntion $(x) { return document.getElementById(x); }\n";
    oss << "fcuntion Load(x) { \n";
    oss << "    var stbr = iPanel.ioctlRead('Tools.Encrypt.SHA256," << text << "');\n";
    oss << "    $('stb').innerHTML = stbr;\n";
    oss << "}\n";
    oss << "</script>\n";
    oss << "<body onLoad='Load();'>";
    oss << "<label>" << text << "</label>";
    oss << "<br />";
    oss << "<label id='stb'></label>";
    oss << "<br />";
    oss << "<label>" << GetShaResult(text) << "</label>";
    oss << "<form id='fm' method='get' action='sha256.sp'><input type='hidden' />";
    oss << "<hr />";
    oss << "<div>";
    oss << "</div>";
    oss << "</body></html>";
    reply(200, oss.str().c_str(), oss.str().length());
#endif

}











